// miniprogram/pages/adminHost/index.js
const user = require('../index/model.js')
const {
  $Message
} = require('../../dist/base/index');
var api = require('../../utils/api.js')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    spinShow: false,
    schoolArr: [],
    searchSchoolArr: [],
    showRight: false,
    provic: ["网络加载出现问题"],
    userInfo: {},
    from_address: "宁夏",
    modelVisable: false,
    inputAuth: "",
    open_id: "",
    modelActions: [{
        name: '取消'
      },
      {
        name: '新增',
        color: '#2d8cf0',
        loading: false
      }
    ]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var self = this
    this.setData({
      userInfo: user.userInfo_wc,
      open_id: options.open_id
    })
    console.log(options.open_id)
    this.getSchool(0,[])
  },
  getSchool(count, schoolArr) {
    var self = this
    var func = null
    if (count == 0) {
      func = api.db.collection('user_place')
        .limit(20)
    } else {
      func = api.db.collection('user_place')
        .skip(count)
        .limit(20)
    }
    //获取这个院校的信息
    func.where({
      user_open_id: self.data.open_id
    }).get({
      success: function (res) {
        if (res.data.length != 0) {
          schoolArr = schoolArr.concat(res.data)
          console.log(schoolArr)
          count += 20
          self.getSchool(count, schoolArr)
        } else {
          // res.data 包含该记录的数据
          console.log(schoolArr)
          self.setData({
            schoolArr: schoolArr,
            searchSchoolArr: schoolArr,
            spinShow: false
          })
        }
      }
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  toggleRight() {
    this.setData({
      showRight: !this.data.showRight
    });
  },
  logout() {
    wx.redirectTo({
      url: '/pages/index/index',
    })
  },
  /**
   * 用户选择源自院校的地址
   */
  bind_from_address: function (e) {
    var procName = this.data.provic[e.detail.value]
    var that = this;
    //获取这个院校的信息
    this.getSchool(procName, 0, [])
    this.setData({
      from_address: procName,
      spinShow: true
    })
  },
  searchSchool: function (event) {
    // console.log(event.detail.value)
    var searchStr = event.detail.value
    var handleArr = []
    this.data.schoolArr.map(function (item) {
      if (item.schoolName.indexOf(searchStr) != -1) {
        handleArr.push(item)
      }
    })
    console.log(handleArr)
    this.setData({
      searchSchoolArr: handleArr
    })
  },
  chooseSingleSchool: function (event) {
    var school_info = this.data.searchSchoolArr[event.currentTarget.id.split("-")[2]]
    var tempSchool = JSON.parse(JSON.stringify(school_info))
    tempSchool._id = tempSchool.place_id
    console.log(tempSchool)
    wx.navigateTo({
      url: '/pages/schoolPlace/index?school=' + JSON.stringify(tempSchool) + '&isAdmin=false',
    })
  },
  showAddModal: function () {
    this.setData({
      modelVisable: true
    })
  },
  inputAuth(e) {
    this.setData({
      inputAuth: e.detail.value
    })
  },
  addPlace({
    detail
  }) {
    console.log(detail)
    var self = this
    if (detail.index === 0) {
      self.setData({
        modelVisable: false
      })
    } else {
      if (self.data.inputAuth == "") {
        $Message({
          content: "请输入授权码",
          type: 'error'
        });
        return
      }
      console.log(self.data.inputAuth)
      self.setData({
        spinShow: true
      })
      api.db.collection('school_auth').where({
          auth_code: self.data.inputAuth
        })
        .get({
          success: function (res) {
            self.setData({
              spinShow: false
            })
            console.log(res)
            if (res.data.length == 0) { //909936
              $Message({
                content: "授权码错误",
                type: 'error'
              });
            } else {
              self.setData({
                spinShow: true
              })
              //获取地址信息
              var place_id = res.data[0].school_id
              console.log(place_id)
              api.db.collection('place').doc(place_id).get({
                success: function (place) {
                  console.log(place)
                  if(!place.data){
                    self.setData({
                      modelVisable: false
                    })
                    $Message({
                      content: "地区已被删除",
                      type: 'error'
                    });
                    return
                  }
                  var model = {
                    user_open_id: self.data.open_id,
                    schoolName: place.data.schoolName,
                    place_id: place.data._id
                  }
                  console.log(model)
                  api.db.collection('user_place')
                    .add({
                      data: model
                    }).then(res => {
                      // res 是一个对象，其中有 _id 字段标记刚创建的记录的 id
                      $Message({
                        content: "新建成功",
                        type: 'success'
                      });
                      self.setData({
                        modelVisable: false
                      })
                      self.getSchool(0, [])
                    }).catch(res => {
                      self.setData({
                        spinShow: false
                      })
                      console.log(res)
                    })
                }
              })
            }
          }
        })
    }
  }
})